package omg.ligong.db;

import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.Date;

/**
 * 池的访问.客户程序可以调用getInstance()方法访问本类的唯一实例.
 */
public class ConnectionManager {
	static private ConnectionManager instance; // 唯一实例
	public final static String POOL_NAME = "MySQL";
	public final static String USERNAME = "username";
	public final static String PASSWORD = "password";
	public final static String URL = "url";
	public final static String DRIVER_CLASS_NAME = "driverClassName";
	public final static String MAX_CONN = "maxConn";
	public final static String LOG_FILE = "logFile";
	private PrintWriter log;
	private Hashtable pools = new Hashtable();

	/**
	 * 返回唯一实例.如果是第一次调用此方法,则创建实例
	 * 
	 * @return DBConnectionManager 唯一实例
	 */
	static synchronized public ConnectionManager getInstance() {
		if (instance == null) {
			synchronized (ConnectionManager.class) {
				if (instance == null) {
					instance = new ConnectionManager();
				}
			}
		}
		return instance;
	}

	/**
	 * 建构函数私有以防止其它对象创建本类实例
	 */
	private ConnectionManager() {
		try {
			init();
		} catch (Exception e) {
			throw new RuntimeException("连接池未创建成功");
		}
	}

	/**
	 * 将连接对象返回给由名字指定的连接池
	 * 
	 * @param con
	 *            连接对象
	 */
	void freeConnection(Connection con) {
		ConnectionPool pool = (ConnectionPool) pools.get(POOL_NAME);
		if (pool != null) {
			pool.freeConnection(con);
		}
	}

	/**
	 * 获得一个可用的(空闲的)连接.如果没有可用连接,且已有连接数小于最大连接数 限制,则创建并返回新连接
	 * 
	 * @return Connection 可用连接或null
	 */
	public Connection getConnection() {
		ConnectionPool pool = (ConnectionPool) pools.get(POOL_NAME);
		if (pool != null) {
			return pool.getConnection();
		}
		return null;
	}

	/**
	 * 获得一个可用连接.若没有可用连接,且已有连接数小于最大连接数限制, 则创建并返回新连接.否则,在指定的时间内等待其它线程释放连接.
	 * 
	 * @param time
	 *            以毫秒计的等待时间
	 * @return Connection 可用连接或null
	 */
	Connection getConnection(long time) {
		ConnectionPool pool = (ConnectionPool) pools.get(POOL_NAME);
		if (pool != null) {
			return pool.getConnection(time);
		}
		return null;
	}

	/**
	 * 关闭所有连接,撤销驱动程序的注册
	 */
	public synchronized void releaseInstance() {
		Enumeration allPools = pools.elements();
		while (allPools.hasMoreElements()) {
			ConnectionPool pool = (ConnectionPool) allPools.nextElement();
			pool.release();
		}
		Enumeration drivers = DriverManager.getDrivers();
		while (drivers.hasMoreElements()) {
			Driver driver = (Driver) drivers.nextElement();
			try {
				DriverManager.deregisterDriver(driver);
				log("撤销JDBC驱动程序 " + driver.getClass().getName() + "的注册");
			} catch (SQLException e) {
				log(e, "无法撤销下列JDBC驱动程序的注册: " + driver.getClass().getName());
			}
		}
		log.close();
		instance = null;
	}

	/**
	 * 根据指定属性创建连接池实例.
	 * 
	 * @param props
	 *            连接池属性
	 */
	private void createPools(Properties props) {
		String url = props.getProperty(ConnectionManager.URL);
		if (url == null) {
			log("没有为连接池" + POOL_NAME + "指定URL");
			return;
		}
		String username = props.getProperty(ConnectionManager.USERNAME);
		String password = props.getProperty(ConnectionManager.PASSWORD);
		String maxConn = props.getProperty(ConnectionManager.MAX_CONN, "0");
		String driverClassName = props
				.getProperty(ConnectionManager.DRIVER_CLASS_NAME);
		String logFile = props.getProperty(ConnectionManager.LOG_FILE);
		if (logFile == null) {
			this.log = new PrintWriter(System.out);
		} else {
			try {
				this.log = new PrintWriter(new FileWriter(logFile, true));
			} catch (Exception e) {
				this.log = new PrintWriter(System.out);
			}
		}
		int max;
		try {
			max = Integer.parseInt(maxConn);
		} catch (NumberFormatException e) {
			log("错误的最大连接数限制: " + maxConn + " .连接池: " + POOL_NAME);
			max = 0;
		}
		ConnectionPool pool = new ConnectionPool(POOL_NAME, url, username,
				password, max, driverClassName);
		pools.put(POOL_NAME, pool);
		log("成功创建连接池" + POOL_NAME);
	}

	/**
	 * 读取属性完成初始化
	 */
	private void init() throws Exception {
		InputStream is = getClass().getResourceAsStream("jdbc.property");
		try {
			Properties dbProps = new Properties();
			dbProps.load(is);
			String logFile = dbProps.getProperty("logFile",
					"ConnectionManager.log");
			System.out.print(logFile);
			try {
				log = new PrintWriter(new FileWriter(logFile, true), true);
			} catch (IOException e) {
				System.err.println("无法打开日志文件: " + logFile);
				log = new PrintWriter(System.err);
			}
			loadDrivers(dbProps);
			createPools(dbProps);
			System.out.print("读取数据成功！");
		} catch (Exception e) {
			System.err.println("不能读取属性文件. "
					+ "请确保db.properties在CLASSPATH指定的路径中");
			return;
		} finally {
			is.close();
		}

	}

	/**
	 * 装载和注册所有JDBC驱动程序
	 * 
	 * @param props
	 *            属性
	 */
	private void loadDrivers(Properties props) {
		String driverClass = props.getProperty(DRIVER_CLASS_NAME);
		try {
			Driver driver = (Driver) Class.forName(driverClass).newInstance();
			DriverManager.registerDriver(driver);
			log("成功注册JDBC驱动程序" + driverClass);
		} catch (Exception e) {
			log("无法注册JDBC驱动程序: " + driverClass + ", 错误: " + e);
		}

	}

	/**
	 * 将文本信息写入日志文件
	 */
	private void log(String msg) {
		log.println(new Date() + ": " + msg);
	}

	/**
	 * 将文本信息与异常写入日志文件
	 */
	private void log(Throwable e, String msg) {
		log.println(new Date() + ": " + msg);
		e.printStackTrace(log);
	}

	public PrintWriter getLogger() {
		return this.log;
	}

	/**
	 * 此内部类定义了一个连接池.它能够根据要求创建新连接,直到预定的最 大连接数为止.在返回连接给客户程序之前,它能够验证连接的有效性.
	 */
	class ConnectionPool {
		private int checkedOut;
		private Vector freeConnections = new Vector();
		private int maxConn;
		private String name;
		private String password;
		private String url;
		private String user;
		private String driverClassName;

		/**
		 * 创建新的连接池
		 * 
		 * @param name
		 *            连接池名字
		 * @param url
		 *            数据库的JDBC URL
		 * @param user
		 *            数据库帐号,或 null
		 * @param password
		 *            密码,或 null
		 * @param maxConn
		 *            此连接池允许建立的最大连接数
		 */
		public ConnectionPool(String name, String url, String user,
				String password, int maxConn, String driverClassName) {
			this.driverClassName = driverClassName;
			this.name = name;
			this.url = url;
			this.user = user;
			this.password = password;
			this.maxConn = maxConn;
		}

		public String getDriverClassName() {
			return this.driverClassName;
		}

		/**
		 * 将不再使用的连接返回给连接池
		 * 
		 * @param conn
		 *            客户程序释放的连接
		 */
		public synchronized void freeConnection(Connection conn) {
			// 将指定连接加入到向量末尾
			freeConnections.addElement(conn);
			checkedOut--;
			notifyAll();
		}

		/**
		 * 从连接池获得一个可用连接.如没有空闲的连接且当前连接数小于最大连接 数限制,则创建新连接.如原来登记为可用的连接不再有效,则从向量删除之,
		 * 然后递归调用自己以尝试新的可用连接.
		 */
		public synchronized Connection getConnection() {
			Connection conn = null;
			if (freeConnections.size() > 0) {
				// 获取向量中第一个可用连接
				conn = (Connection) freeConnections.firstElement();
				freeConnections.removeElementAt(0);
				try {
					if (conn.isClosed()) {
						log("从连接池" + name + "删除一个无效连接");
						// 递归调用自己,尝试再次获取可用连接
						conn = getConnection();
					}
				} catch (SQLException e) {
					log("从连接池" + name + "删除一个无效连接");
					// 递归调用自己,尝试再次获取可用连接
					conn = getConnection();
				}
			} else if (maxConn == 0 || checkedOut < maxConn) {
				conn = newConnection();
			}
			if (conn != null) {
				checkedOut++;
			}
			return conn;
		}

		/**
		 * 从连接池获取可用连接.可以指定客户程序能够等待的最长时间 参见前一个getConnection()方法.
		 * 
		 * @param timeout
		 *            以毫秒计的等待时间限制
		 */
		public synchronized Connection getConnection(long timeout) {
			long startTime = new Date().getTime();
			Connection conn;
			while ((conn = getConnection()) == null) {
				try {
					wait(timeout);
				} catch (InterruptedException e) {
				}
				if ((new Date().getTime() - startTime) >= timeout) {
					// wait()返回的原因是超时
					return null;
				}
			}
			return conn;
		}

		/**
		 * 关闭所有连接
		 */
		public synchronized void release() {
			Enumeration allConnections = freeConnections.elements();
			while (allConnections.hasMoreElements()) {
				PooledConnection conn = (PooledConnection) allConnections.nextElement();
				try {
					conn.realClose();
					log("关闭连接池" + name + "中的一个连接");
				} catch (SQLException e) {
					log(e, "无法关闭连接池" + name + "中的连接");
				}
			}
			freeConnections.removeAllElements();
		}

		/**
		 * 创建新的连接
		 */
		private Connection newConnection() {
			Connection conn = null;
			try {
				if (user == null) {
					conn = DriverManager.getConnection(url);
				} else {
					conn = DriverManager.getConnection(url, user, password);
				}
				log("连接池" + name + "创建一个新的连接");
			} catch (SQLException e) {
				log(e, "无法创建下列URL的连接: " + url);
				e.printStackTrace();
				return null;
			}
			return new PooledConnection(conn);
		}
	}
}
